// pages/funcs/apply.js

const App = getApp()
import Util from '../../utils/util'
Page({
  data: {
    init: false,
    loading: false,

    step: 0,
    id: '',

    full: '',
    osno: '',
    olc: '',
    ocr: {},

    cert: '',

    auto: '',

    leader: true,

    name: '',
    addr: '',
    area: '',
    locs: '',
    himg: '',
    audit: {},

    agree: false,

    timer: undefined,
    timeNum:10

  },
  onLoad() {
    this.execLoad()
  },
  onShow() {
    if (this.data.step == 2) {
      this.execLoad()
    }
  },
  onUnload() {
    if (this.data.timer) {
      clearTimeout(this.data.timer)
      clearInterval(this.data.timer)
    }
  },

  execLoad() {
    App.doPost({
      uri: '/app/merchant/apply/info',
      body: {},
      fnSucc: resp => {
          console.log(resp.data,"入驻合同信息");
        if (resp.data.step == 5) {
          this.setData({
            init: true,
            step: resp.data.step,
            id: resp.data.id
          })
          // 审核通过10s后默认跳转返回
          this.data.timer = setInterval(() => {
            // this.data.timeNum--
            this.setData({
              timeNum:this.data.timeNum-1
            })
            console.log(this.data.timeNum)
            if(this.data.timeNum<=0){
              this.toIndex()
              clearInterval(this.data.timer)
              this.data.timer=undefined
            }
          },1000);
          return
        } else if (resp.data.step == 4) {
          if (resp.data.audit.state != 0) {
            this.setData({
              name: resp.data.name,
              addr: resp.data.addr,
              area: resp.data.area.code ? resp.data.area.code + '' : '',
              locs: resp.data.locs,
              himg: resp.data.himg,
            })
          }
          this.setData({
            leader: resp.data.leader,
            audit: resp.data.audit
          })


        } else if (resp.data.step == 3) {
          wx.redirectTo({
            url: `/pages/funcs/fdd?src=apply&url=${encodeURIComponent(resp.data.auto)}`,
          })
          return
        } else if (resp.data.step == 2) {

          wx.redirectTo({
            url: `/pages/funcs/fdd?src=apply&url=${encodeURIComponent(resp.data.cert)}`,
          })
          return
        }
        this.setData({
          init: true,
          step: resp.data.step,
          agree: false,
          id: resp.data.id || ''
        })
      }
    })
  },
  doBaseSave() {
    if (!this.data.olc) {
      Util.Notify.warn(`请上传营业执照`)
      return
    }
    if (!this.data.osno || !this.data.full) {
      Util.Notify.warn(`营业执照不能识别，请重新上传`)
      return
    }
    if (this.data.osno != this.data.ocr.sno || this.data.full != this.data.ocr.name) {
      wx.showModal({
        title: '温馨提示',
        cancelText: '取消',
        confirmText: '确认无误',
        confirmColor: '#0081ff',
        content: '您已修改自动识别的信息，请确认是否资料无误',
        success: (res) => {
          if (res.confirm) {
            this.execBaseSave()
          }
        }
      })
      return
    }

    this.execBaseSave()
  },
  // 上传营业执照后下一步
  execBaseSave() {
    this.setData({
      loading: true
    })
    App.doPost({
      uri: '/app/merchant/apply/base/save',
      body: {
        appid: App.Global.AppId,
        ouid: App.Global.OpenId,
        full: this.data.full,
        osno: this.data.osno,
        olc: this.data.olc
      },
      fnSucc: (resp) => {
        if (resp.data.user) {
          let user = resp.data.user
          // let cert = resp.data.cert
          wx.setStorageSync('App.Uid', user.id)
          wx.setStorageSync('App.Token', user.token)
          wx.setStorageSync('App.Name', user.name)
          wx.setStorageSync('App.User', JSON.stringify(user))
          App.Global.User = user
          App.Global.Token = user.token
        }
        // 跳转法大大认证
        wx.redirectTo({
          url: `/pages/funcs/fdd?src=apply&url=${encodeURIComponent(resp.data.cert)}`,
        })
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },
  doClear() {
    wx.showModal({
      title: '温馨提示',
      cancelText: '点错了',
      confirmText: '确认清空',
      confirmColor: '#e54d42',
      content: '是否清空入驻信息，重新提交',
      success: (res) => {
        if (res.confirm) {
          App.doPost({
            uri: '/app/merchant/apply/clear',
            body: {},
            fnSucc: () => {
              wx.setStorageSync('App.Uid', '')
              wx.setStorageSync('App.Token', 'Guest')
              wx.setStorageSync('App.Name', '')
              wx.setStorageSync('App.User', '{}')
              wx.setStorageSync('App.Users', '[]')
              App.Global.User = {}
              App.Global.Token = 'Guest'
              wx.reLaunch({
                url: '/pages/splash/splash',
              })
            }
          })
        }
      }
    })
  },

  // 申请入驻
  doSubmit() {
    if (!this.data.agree) {
      Util.Notify.warn(`请同意入驻协议`)
      return
    }
    if (!this.data.name) {
      Util.Notify.warn(`请填写门店简称`)
      return
    }
    if (!this.data.locs) {
      Util.Notify.warn(`请选择门店位置`)
      return
    }
    if (!this.data.addr) {
      Util.Notify.warn(`请填写门店地址`)
      return
    }
    if (!this.data.himg) {
      Util.Notify.warn(`请上传门头照片`)
      return
    }
    this.execSubmit()
  },

  
  execSubmit() {
    this.setData({
      loading: true
    })
    App.doPost({
      uri: '/app/merchant/apply/submit',
      body: {
        name: this.data.name,
        addr: this.data.addr,
        area: this.data.area + '',
        locs: this.data.locs,
        himg: this.data.himg,
      },
      fnSucc: (re) => {
        Util.Toast.succ(`提交成功`)
        const DDA = JSON.stringify(re,null,2)
        console.log(DDA,"sdfseg")
        this.execLoad()
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })

  },
  doAgree() {
    this.setData({
      agree: !this.data.agree
    })
  },
  // 前往首页
  toIndex() {
    App.doWxmnLogin(() => {
      wx.reLaunch({
        url: '/pages/splash/splash',
      })
    })
  },
  // 协议跳转
  toAgreement() {
    App.doPost({
      uri: '/app/base/data/config',
      body: {},
      fnSucc: resp => {
        let uri = `${resp.data.web.rzxy}?id=${this.data.id}`
        wx.navigateTo({
          url: `/pages/funcs/web?url=${encodeURIComponent(uri)}`,
        })
      }
    })
  },
  // 入驻协议跳转
  toAuthTmpl() {
    App.doPost({
      uri: '/app/base/data/config',
      body: {},
      fnSucc: resp => {
        let uri = `${resp.data.web.jysq}?id=${this.data.id}`
        wx.navigateTo({
          url: `/pages/funcs/web?url=${encodeURIComponent(uri)}`,
        })
      }
    })
  },
  doCertChange(e) {
    console.log(e.target.dataset,e.detail)
    let type = e.target.dataset.type
    let odata = {}
    odata[type] = e.detail.url
    if (type == 'olc') {
      if (e.detail.ocr.sno) {
        odata["osno"] = e.detail.ocr.sno
        odata["full"] = e.detail.ocr.name
        odata["ocr"] = e.detail.ocr
      } else {
        odata["osno"] = ''
        odata["full"] = ''
      }
    }
    this.setData({
      ...odata
    })
  },
  doPictChange(e) {
    let odata = {}
    odata[e.target.dataset.type] = e.detail.url
    this.setData({
      ...odata
    })
  },

  // 选择地点
  doSelectLocs() {
    let lng = this.data.locs ? parseFloat(this.data.locs.split(',')[0]) : undefined
    let lat = this.data.locs ? parseFloat(this.data.locs.split(',')[1]) : undefined
    wx.chooseLocation({
      longitude: lng,
      latitude: lat,
      success: (res) => {
        let locs = res.longitude.toFixed(6) + ',' + res.latitude.toFixed(6)
        App.doPost({
          uri: '/comm/tool/locs/info',
          body: {
            locs: locs
          },
          fnSucc: resp => {
            this.setData({
              addr: res.address,
              area: resp.data.area.code + '',
              locs: locs
            })
          },
          fnFail: () => {
            Util.Toast.fail('未知地点信息')
          }
        })
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },

})